#include <stdio.h>
#include <stdlib.h>
#include <sys/inotify.h>
#include <linux/limits.h>
#include <unistd.h>

#define EVENT_SIZE (sizeof(struct inotify_event))
#define MAX_EVENT_SIZE  (EVENT_SIZE + NAME_MAX + 1)

void monitor_file(char* file_path){
	int fd = inotify_init();
	if (fd == -1){
		perror("inotify_init failed");
		exit(-1);
	}
	if (inotify_add_watch(fd, file_path, IN_CREATE|IN_DELETE|IN_MODIFY) < 0){
		perror("inotify_add_watch failed");
		exit(-1);
	}

	char* buf = malloc(MAX_EVENT_SIZE);
	int length;
	if ((length = read(fd, buf, MAX_EVENT_SIZE)) < 0){
		perror("read failed");
		exit(-1);
	}
	int i = 0;
	while (i < length){
		struct inotify_event *event = (struct inotify_event *)&buf[i];
		if (event->len){
			if(event->mask & IN_CREATE){
				printf("The file %s was created.\n", event->name);
			}else if(event->mask & IN_DELETE){
				printf("The file %s was deleted.\n", event->name);
			}else if(event->mask & IN_MODIFY){
				printf("The file %s was modified.\n", event->name);
			}else{
				printf("Unknow changed.\n");
			}
		}
		i += EVENT_SIZE + event->len;
	}
	close(fd);
	printf("END\n");
}

int main(int argc, char** argv) {
	if (argc == 1){
		printf("USAGE: filemonitor xxxx, xxx is the monitor file\n");
		exit(-1);
	}

	char* file_path = argv[1];
	monitor_file(file_path);
}
